import 'package:flutter/material.dart';
// import 'package:myapp/cache/cache_manager.dart';
import 'package:myapp/components/Logger/loggers.dart';
import 'package:myapp/dio/api/auth.dart';
import 'package:myapp/store/user_model.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _usernameController =
      TextEditingController(text: '1624362469');
  final TextEditingController _passwordController =
      TextEditingController(text: '147258369TQLtql');

  String _message = '';

  _login(context) async {
    // 这里可以替换成实际的登录验证逻辑，比如调用API验证用户名密码是否有效
    String account = _usernameController.text;
    String password = _passwordController.text;
    try {
      var data = await Auth.loginApi(account, password);
      logger.t(data.token);
      if (data.token != '') {
        setState(() {
          _message = '登录成功！';
        });
        UserModel().saveToken(data.token);
        // Navigator.of(context).pushNamed("/");
      } else {
        setState(() {
          _message = '用户名或密码错误，请重试。';
        });
      }
    } catch (e) {
      logger.t(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            TextField(
              controller: _usernameController,
              decoration: const InputDecoration(
                labelText: '用户名',
              ),
            ),
            const SizedBox(height: 20.0),
            TextField(
              controller: _passwordController,
              decoration: const InputDecoration(
                labelText: '密码',
              ),
              obscureText: true,
            ),
            const SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () => _login(context),
              child: const Text('登录'),
            ),
            const SizedBox(height: 20.0),
            Text(
              _message,
              style: const TextStyle(
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
